package com.vonchange.water.util;

import javax.script.Bindings;
import javax.script.Compilable;
import javax.script.CompiledScript;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.script.SimpleBindings;
import java.util.HashMap;
import java.util.Map;

public class ScriptUtil {
    //language
    public static final String defaultLanguage="groovy";
    private static Compilable engine;
    static {
        ScriptEngineManager manager = new ScriptEngineManager();
        engine  = (Compilable) manager.getEngineByName(defaultLanguage);
    }

    public static Object run(String script, Map<String,Object> args) throws ScriptException {
        CompiledScript compiledScript = engine.compile(script);
        Bindings bindings = new SimpleBindings();
        bindings.putAll(args);
        Object result = compiledScript.eval(bindings);
        if(null==result){
            return null;
        }
        return result;
    }
    public static void main(String[] args) throws ScriptException {
        String text=
                //"class GroovyShell_2 {\n" +
                "\t def sayHello(name,sex,age) {\n" +
                "\t\tprintln 'GroovyShell_2 的sayHello(String name, String sex, int age)方法';\n" +
                "\t\treturn \"name: \" + name + \", sex: \" + sex + \", age: \" + age;\n" +
                "\t}\n" +
                "age>=18";
        //name", "sex", 18
        Map<String,Object> map = new HashMap<>();
        map.put("name","name");
        map.put("sex","sex");
        map.put("age",18);
         Object result=  run(text,map);
        System.out.println(result);
        System.out.println(run("age>=18",map).toString());

    }


}
